const Domain ="https://tran.qiyedaishu.com";
//const Domain = "http://localhost:14836/";

import md5 from "@/utils/md5.js";
const FormatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(FormatNumber).join('/') + ' ' + [hour, minute, second].map(FormatNumber).join(':')
}

const FormatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
String.prototype.RHtml = function () {
  return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, "");
};

String.prototype.ReplaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

String.prototype.Contain = function (str) {
    return this.indexOf(str)>-1?true:false;
};

String.prototype.TranImg = function (str) {
    return this.ReplaceAll("<img","<img style='width:100%;' ");
};

String.prototype.TranImg = function (str) {
    return this.ReplaceAll("<img","<img style='width:100%;' ");
};
String.prototype.IsEmpty = function (str) {
    return (Validate.IsEmpty(str) || str==Domain);
};
Array.prototype.Remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.RemoveAt = function (index) {
    if (isNaN(index) || index >= this.length) {
        return false;
    }
    this.splice(index, 1);
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};

Array.prototype.Max = function () {
  return Math.max.apply(Math, this);
};

Array.prototype.Min = function () {
  return Math.min.apply(Math, this);
};

String.prototype.ToDate = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy-MM-dd");
};
String.prototype.ToDateTwo = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("yyyy.MM.dd");
};
String.prototype.ToDayTime = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("MM-dd hh:mm");
};
String.prototype.ReplacePlus = function () {
	var str=this;
	while(str.indexOf('+')>-1){
		str=str.replace('+','%2B');
	}
	return str;
};
Number.prototype.ToString = function () {
    return this.toString();
};
Number.prototype.ToEmpty = function () {
	if(this==0 || !this){
		return "";
	}else{
		return this+"";
	}
};
//四舍五入保留2位小数
Number.prototype.ToPrice = function () {
    return (Math.round(this * 100) / 100).toFixed(2);
};
Date.prototype.Format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};
Date.prototype.AddDays = function (d) {
    return new Date(this.setDate(this.getDate() + d));
};
function Loading(title){
	uni.showLoading({
	    title: title
	});
};

function HideLoading(){
	uni.hideLoading();
};

function Toast(title, callback){
	uni.showToast({
	    title: title,
		icon: "none",
		position: "bottom",
	    duration: 2000,
		success: function (res) {
			setTimeout(function(){
				callback && callback();
			},1000);
		}
	});
};

function Success(title){
	uni.showToast({
	    title: title,
	    duration: 2000
	});
};

function Fail(title){
	uni.showToast({
	    title: title,
		image: "http://gongxianggudong.qiyedaishu.com/static/image/error.png",
	    duration: 2000
	});
};

function Alert(title, callback){
	uni.showModal({
	    title: "提示",
	    content: title,
		showCancel: false,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            
	        }
	    }
	});
}

function Confirm(title, callback){
	uni.showModal({
	    title: "提示",
	    content: title,
	    success: function (res) {
	        if (res.confirm) {
	            callback && callback();
	        } else if (res.cancel) {
	            
	        }
	    }
	});
}
function LoadMore(data,callback){
	Post(data, json=>{
		callback && callback(json.Data.List);
	});
}
function Post(data, callback) {
  data.ParentID=uni.getStorageSync("ParentID");
  data.Timestamp = new Date().getTime();
  data.Token =  uni.getStorageSync("Token") || '';
  data.Sign = md5.GetSign(data);
  data.Area = "motiandarenku";
  uni.request({
		header: {'Content-Type':'application/x-www-form-urlencoded'},
  		url: Domain+"/tools/API.ashx",
		method:'POST',
  		data: data,
  		success: (json) => {
  			if(json.data.State){
  				callback && callback(json.data);
  			}else{
				if(json.data.Code=="401"){
					Toast(json.data.Msg, item=>{
						if(Ticker(2)){
							uni.navigateTo({
								url:'/pages/login/login'
							})
						}
					});
				}else{
					callback && callback(json.data);
				}
  			}
  		},
  		fail(json) {
  			Toast(json.data.Msg);
  		}
  });
};
function Ticker(Second){
	var OldTime = uni.getStorageSync("Time");
	if(!OldTime){
		uni.setStorageSync("Time",new Date().Format("yyyy-MM-dd hh:mm:ss"));
		return true;
	}else{
		var NewTime=new Date().Format("yyyy-MM-dd hh:mm:ss");
		uni.setStorageSync("Time",NewTime);
		if(DateDiff("s",OldTime, NewTime)>Second){
			return true;
		}else{
			return false;
		}
		
	}
};
function Upload(paths, handle, list, callback){
	var path = paths.pop();
	uni.uploadFile({
		  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
		  filePath: path,
		  name: 'img',
		  formData: {handle:handle},
		  success: json=> {
			  list.push(JSON.parse(json.data).Data.Path);
			  if(paths.length > 0){
			      Upload(paths, handle, list, callback);
			  }else{
			      callback(list);
			  }
		  }
	});
};
function OneUpload(path, handle, callback){
	uni.uploadFile({
		  url: Domain + '/Tools/Upload.ashx', //仅为示例，非真实的接口地址
		  filePath: path,
		  name: 'img',
		  formData: {handle:handle},
		  success: json=> {
			  if(callback){callback(JSON.parse(json.data).Data.Path);}
		  }
	});
};
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return "";
}

function GCJ02ToBaiDu(value) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var ll = value.split(",");
    var x = ll[1], y = ll[0];
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    return  (z * Math.sin(theta) + 0.006)+ ',' + (z * Math.cos(theta) + 0.0065);
}
function SetTabBarBadge(Count){
	if(Count>0){
		uni.setTabBarBadge({
			index: 3,
			text: Count.toString()
		});
		// #ifdef APP-PLUS
		plus.runtime.setBadgeNumber(Count);
		// #endif
	}else{
		uni.removeTabBarBadge({
			index:3
		});
	}
}
function ListToImgs(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Name+"*"+item.Path);
	});
	return array.join(",");
};
function ListToPaths(list){
	var array=[];
	list.forEach(item=>{
		array.push(item.Path);
	});
	return array.join(",");
};
function TranList(list){
	var array=[];
	list.forEach(item=>{
		array.push(item);
	});
	return array;
};

function CheckUpdate(){
	const updateManager = uni.getUpdateManager();
	updateManager.onCheckForUpdate(function (res) {
	  // 请求完新版本信息的回调
	});
	
	updateManager.onUpdateReady(function (res) {
	  uni.showModal({
	    title: '更新提示',
	    content: '发现新版本，点击确定后将重启？',
	    success(res) {
	      if (res.confirm) {
	        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
			
	        updateManager.applyUpdate();
	      }
	    }
	  });
	
	});
	
	updateManager.onUpdateFailed(function (res) {
	  // 新的版本下载失败
	});
};
function DateDiff(interval,date1,date2){
	var dt1 =  Date.parse(date1.replace(/-/g, '/'));
	var dt2 = Date.parse(date2.replace(/-/g, '/'));
	var long = parseInt(dt2 - dt1); //相差毫秒
	switch(interval.toLowerCase()){
	case "y": return parseInt(long/1000/60/60/24/365);
	case "m": return parseInt(long/1000/60/60/24/30);
	case "d": return parseInt(long/1000/60/60/24);
	case "w": return parseInt(long/1000/60/60/24/7);
	case "h": return parseInt(long/1000/60/60);
	case "n": return parseInt(long/1000/60);
	case "s": return parseInt(long/1000);
	case "l": return parseInt(long);
	}
}
function SetParam(options){
	if (options.scene) {
	    var scene = decodeURIComponent(options.scene);
	    uni.setStorageSync("ParentID",scene);
	}
	if(options.ParentID){
		uni.setStorageSync("ParentID",options.ParentID);
	}
};

function AdSkip(item){
	if(item.Type==1){
		uni.navigateTo({
			url:'/pages/bookinfo/bookinfo?ID='+item.SID
		})
	}else if(item.Type==2){
		uni.navigateTo({
			url:'/pages/index/recommendbook?ID='+item.SID
		})
	}else if(item.Type==3){
		uni.navigateTo({
			url:'/pages/news/newsinfo?ID='+item.SID
		})
	}
};
function Auth(){
	if(App.User.ID>0 && App.User.CardNum!='' && App.User.OpenIDF==''){
		Confirm("授权给鲸鸿飞书公众号以接收通知？",json=>{
			uni.navigateTo({
				url:'/pages/index/auth'
			})
		});
	}
};
function ToSuccess(Url, TipText, BtnText, Delta){
	uni.navigateTo({
		url:"/pages/index/success?Url="+Url+"&TipText="+TipText+"&BtnText="+BtnText+"&Delta="+Delta
	})
};
function ToPaySuccess(Url, Ewm, TipText, BtnText, Delta){
	uni.navigateTo({
		url:"/pages/index/paysuccess?Ewm="+Ewm+"&Url="+Url+"&TipText="+TipText+"&BtnText="+BtnText+"&Delta="+Delta
	})
};
module.exports = {
  Domain,
  FormatTime,
  Alert,
  Confirm,
  Toast,
  Success,
  Fail,
  Loading,
  HideLoading,
  Upload,
  OneUpload,
  Post,
  GetQueryString,
  GCJ02ToBaiDu,
  SetTabBarBadge,
  ListToImgs,
  ListToPaths,
  TranList,
  LoadMore,
  CheckUpdate,
  DateDiff,
  SetParam,
  AdSkip,
  Auth,
  ToSuccess,
  ToPaySuccess
}
